//
//  OAuthViewController.swift
//  Sinaweibo
//
//  Created by 谌桃 on 15/11/28.
//  Copyright © 2015年 ryan.chen. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController{
    
    let webView = UIWebView()
    
    override func loadView() {
        
        self.view = webView
        webView.delegate = self
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "back")

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
        loadOAuthPage()
    }
    
    //返回到上个页面
    func back(){
    
        dismissViewControllerAnimated(true, completion: nil)
    }

    //MARK:测试用的 自动填充 发布的时候记得关闭
    //webView中调用js 的 代码 进行自动填充
    func defaultAccount(){
    
        //本地代码和js 进行通讯
        let urlString = "document.getElementById('userId').value='18610308736',document.getElementById('passwd').value='032678'"
        
        webView.stringByEvaluatingJavaScriptFromString(urlString)
    }
    
    
    //MARK: 加载授权网页
    private func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        if let url = NSURL(string: urlString) {
            
            let request = NSURLRequest(URL: url)
            
            webView.loadRequest(request)
        }
    }
}

//MARK: 使用extension 为当前类直接扩展协议方法
extension OAuthViewController: UIWebViewDelegate{

    //webView开始加载 , 显示指示器
    func webViewDidStartLoad(webView: UIWebView){
    
        SVProgressHUD.show()
    }
 
    //webView加载完成, 销毁指示器
    func webViewDidFinishLoad(webView: UIWebView){
        
        SVProgressHUD.dismiss()
    }
    
    
    //通过截取 request , 获取授权码code, 再通过授权码取得令牌  Token , 取得有  时效性 令牌 才证明登录成功, 拥有 令牌 token就不需要重复登录
    
    //print(request)的结果:  <NSMutableURLRequest: 0x7fb4497c7390> { URL: https://m.baidu.com/?code=0f5730af0e8fe45f48b30bd08672eb9c&from=844b&vit=fps }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
//        print(request)
        
        //js  调用  本地代码 , 重定向url , 通过截取该url 执行本地代码进行页面的跳转等操作 , 基本都是web 和 本地代码配合着用
        let urlString = request.URL?.absoluteString ?? ""
        
        //屏蔽不希望加载的页面
        if urlString.hasPrefix("https://api.weibo.com/") {
        
            return true
        }
        
        if !urlString.hasPrefix("http://www.baidu.com/") {
        
            return false
        }
        
        //代码进入到这步, 表示加载的url就是我们想要的包含 授权码的url
        
        //获取授权码
        
        guard let query = request.URL?.query else{
        
            //获取不到参数列表  直接返回false
            return false
        }
        
        print(query)
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        
        print(code)
        
        
        //请求用户token
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            
            if error != nil {
                //网络请求失败
                SVProgressHUD.showErrorWithStatus(errorTip)
                return
            }
            //发出切换页面消息
            // dismissViewControllerAnimated 页面并不会立即被回收
            self.dismissViewControllerAnimated(false) { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
                
                //通知是同步
                print("come  here !!!")
            }
        }
        
        return false
    }
    
}





